<?php

namespace App\Bucket\Utils;

use Fresh\Facade\Di;

class MyToolkit
{
    public static function mapArrayToObjects($items, $object)
    {
        $className = get_class($object);
        $class = Di::get('classMetaManager')->getClass($className);
        foreach ($class->properties as $property) {
            $object->{$property->name} = $items[$property->name];
        }

        return $object;
    }

    public static function getDiffDateCount($startDate, $endDate)
    {
        if (strtotime($startDate) > strtotime($endDate)) {
            list($startDate, $endDate) = [$endDate, $startDate];
        }
        $dateTimeStart = date_create($startDate);
        $dateTimeEnd = date_create($endDate);
        $diff = date_diff($dateTimeStart, $dateTimeEnd, true);

        return $diff->format("%a") + 1;
    }

    /**
     * 转换成浮点数
     * @param string $number
     * @param int $precision
     * @return string
     */
    public static function convert2float($number, $precision = 6)
    {
        $result = null;
        $number = floatval($number);
        if (is_nan($number)) {
            $number = 0;
        } elseif (is_infinite($number)) {
            $number = 1;
        }
        return sprintf("%.{$precision}f", $number);
    }
}
